package com.tsj.model.model.vo;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;

import java.io.*;
import java.net.URL;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ExcelImageExtractor {

    public static void main(String[] args) throws IOException {
        Path excelPath = Paths.get("input.xlsx"); // 也可改为 .xls
        Path outputDir = Paths.get("images");
        Files.createDirectories(outputDir);
        URL url = new URL("http://192.168.0.63:9000/digital-middle-platform/files/resource/resource/68fae809e4b0c594140f49b4.xlsx");
        try (InputStream is = url.openStream();
             Workbook workbook = WorkbookFactory.create(is)) {

            if (workbook instanceof XSSFWorkbook xwb) {
                processXlsx(xwb, outputDir);
            } else if (workbook instanceof HSSFWorkbook hwb) {
                processXls(hwb, outputDir);
            }
        }
    }

    private static void processXlsx(XSSFWorkbook xwb, Path outputDir) throws IOException {
        AtomicInteger imgIdx = new AtomicInteger(1);
        for (int s = 0; s < xwb.getNumberOfSheets(); s++) {
            XSSFSheet sheet = xwb.getSheetAt(s);
            String sheetName = sheet.getSheetName();

            for (POIXMLDocumentPart rel : sheet.getRelations()) {
                if (!(rel instanceof XSSFDrawing drawing)) continue;
                for (XSSFShape shape : drawing.getShapes()) {
                    if (!(shape instanceof XSSFPicture pic)) continue;
                    XSSFPictureData pData = pic.getPictureData();
                    String ext = pData.suggestFileExtension();
                    byte[] data = pData.getData();

                    XSSFClientAnchor anchor = pic.getClientAnchor();
                    // 起始单元格（Excel 行列从 1 开始）
                    int fromRow = anchor.getRow1() + 1;
                    int fromCol = anchor.getCol1() + 1;

                    // 建议文件名：优先用锚点说明（可能为空），否则自动生成
                    String suggestName = anchor.getAnchorType().name(); // 常见为“替代文本”
                    if (suggestName == null || suggestName.isBlank()) {
                        suggestName = anchor.toString(); // 其次尝试描述
                    }
                    String fileName = (suggestName != null && !suggestName.isBlank())
                            ? sanitize(suggestName) + "." + ext
                            : String.format("img_%d_%s_%d.%s", imgIdx.getAndIncrement(), sheetName, fromRow, ext);

                    Path out = outputDir.resolve(fileName);
                    Files.write(out, data);

                    System.out.printf("XLSX: Sheet=%s, Cell=[%d,%d], Name=%s, Ext=%s, Size=%d bytes%n",
                            sheetName, fromRow, fromCol, fileName, ext, data.length);
                }
            }
        }
    }

    private static void processXls(HSSFWorkbook hwb, Path outputDir) throws IOException {
        // XLS 需要将“所有图片”与“每个 sheet 的锚点”做关联
        List<HSSFPictureData> allPics = hwb.getAllPictures();
        for (int s = 0; s < hwb.getNumberOfSheets(); s++) {
            HSSFSheet sheet = hwb.getSheetAt(s);
            String sheetName = sheet.getSheetName();
            HSSFPatriarch drawing = sheet.getDrawingPatriarch();
            if (drawing == null) continue;

            for (HSSFShape shape : drawing.getChildren()) {
                if (!(shape instanceof HSSFPicture pic)) continue;
                HSSFPictureData pData = pic.getPictureData();
                String fileName = pic.getFileName(); // 可能为空

                HSSFClientAnchor anchor = pic.getClientAnchor();
                // HSSF 锚点行列为 short，转换为 1-based
                int fromRow = anchor.getRow1() + 1;
                int fromCol = anchor.getCol1() + 1;

                // 若文件名为空，尝试生成一个
                if (fileName == null || fileName.isBlank()) {
                    fileName = "img_" + (allPics.indexOf(pData) + 1) + "." + pData.suggestFileExtension();
                }

                Path out = outputDir.resolve(fileName);
                Files.write(out, pData.getData());

                System.out.printf("XLS:  Sheet=%s, Cell=[%d,%d], Name=%s, Size=%d bytes%n",
                        sheetName, fromRow, fromCol, fileName, pData.getData().length);
            }
        }
    }

    // 简单清理非法字符，避免文件系统问题
    private static String sanitize(String name) {
        if (name == null) return "image";
        return name.replaceAll("[\\\\/:*?\"<>|]", "_");
    }
}